#include "ClipPlaneShader.h"
#include <d3dx11async.h>

using namespace Graphics;

ClipPlaneShader::ClipPlaneShader(void)
	:Shader("ClipPlaneShader",""), 
	 mClipPlaneBuffer(NULL)
{
}

ClipPlaneShader::~ClipPlaneShader(void)
{
}

bool ClipPlaneShader::Initialize()
{
	Graphics::D3DDevice* device = GetPlatform()->GetDevice()->As<Graphics::D3DDevice>();
	// Initialize the vertex and pixel shaders.
	return InitializeShader(device->GetWindowsSettings().WindowHandle, "..\\..\\assets\\shaders\\clipplane.vs", "..\\..\\assets\\shaders\\clipplane.ps");
}

void ClipPlaneShader::Deinitialize()
{
	DeinitializeShader();
}

bool ClipPlaneShader::Render(int indexCount, D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix, D3DXMATRIX projectionMatrix, ID3D11ShaderResourceView* texture, D3DXVECTOR4 clipPlane)
{
	Graphics::D3DDevice* device = GetPlatform()->GetDevice()->As<Graphics::D3DDevice>();

	// Set the shader parameters that it will use for rendering.
	bool result = SetShaderParameters( worldMatrix, viewMatrix, projectionMatrix, texture, clipPlane);

	// Now render the prepared buffers with the shader.
	result = RenderShader(device, indexCount);

	return result;
}

bool ClipPlaneShader::InitializeShader(HWND hwnd, const char* vsFilename, const char*  psFilename)
{
	Graphics::D3DDevice* device = GetPlatform()->GetDevice()->As<Graphics::D3DDevice>();
	if(Shader::InitializeShader(device, hwnd, vsFilename, psFilename))
	{

		// Create the vertex input layout description.
		// This setup needs to match the VertexType stucture in the ModelClass and in the shader.
		D3D11_INPUT_ELEMENT_DESC polygonLayout[3];
		polygonLayout[0].SemanticName = "POSITION";
		polygonLayout[0].SemanticIndex = 0;
		polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
		polygonLayout[0].InputSlot = 0;
		polygonLayout[0].AlignedByteOffset = 0;
		polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
		polygonLayout[0].InstanceDataStepRate = 0;

		polygonLayout[1].SemanticName = "COLOR";
		polygonLayout[1].SemanticIndex = 0;
		polygonLayout[1].Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
		polygonLayout[1].InputSlot = 0;
		polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
		polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
		polygonLayout[1].InstanceDataStepRate = 0;

		polygonLayout[2].SemanticName = "TEXCOORD";
		polygonLayout[2].SemanticIndex = 0;
		polygonLayout[2].Format = DXGI_FORMAT_R32G32_FLOAT;
		polygonLayout[2].InputSlot = 0;
		polygonLayout[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
		polygonLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
		polygonLayout[2].InstanceDataStepRate = 0;

		// Get a count of the elements in the layout.
		unsigned int numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]);

		// Create the vertex input layout.
		HRESULT result = device->GetDevice()->CreateInputLayout(polygonLayout, 
											numElements, 
											mVertexShaderBuffer->GetBufferPointer(), 
											mVertexShaderBuffer->GetBufferSize(), 
											&mLayout);
		if(FAILED(result))
		{
			return false;
		}

		// Release the vertex shader buffer and pixel shader buffer since they are no longer needed.
		mVertexShaderBuffer->Release();
		mVertexShaderBuffer = NULL;

		mPixelShader->Release();
		mPixelShaderBuffer = NULL;

		// Create a texture sampler state description.
		D3D11_SAMPLER_DESC samplerDesc;
		samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
		samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
		samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
		samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
		samplerDesc.MipLODBias = 0.0f;
		samplerDesc.MaxAnisotropy = 1;
		samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
		samplerDesc.BorderColor[0] = 0;
		samplerDesc.BorderColor[1] = 0;
		samplerDesc.BorderColor[2] = 0;
		samplerDesc.BorderColor[3] = 0;
		samplerDesc.MinLOD = 0;
		samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;

		// Create the texture sampler state.
		result = device->GetDevice()->CreateSamplerState(&samplerDesc, &mSampleState);
		if(FAILED(result))
		{
			return false;
		}

		// Setup the description of the clip plane dynamic constant buffer that is in the vertex shader.
		D3D11_BUFFER_DESC clipPlaneBufferDesc;
		clipPlaneBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
		clipPlaneBufferDesc.ByteWidth = sizeof(ClipPlaneBufferType);
		clipPlaneBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
		clipPlaneBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
		clipPlaneBufferDesc.MiscFlags = 0;
		clipPlaneBufferDesc.StructureByteStride = 0;

		// Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
		result = device->GetDevice()->CreateBuffer(&clipPlaneBufferDesc, NULL, &mClipPlaneBuffer);
		if(FAILED(result))
		{
			return false;
		}

		return true;
	}
	return false;
}

void ClipPlaneShader::DeinitializeShader()
{
	if(mClipPlaneBuffer)
	{
		mClipPlaneBuffer->Release();
		mClipPlaneBuffer = NULL;
	}
}

bool ClipPlaneShader::SetShaderParameters(D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix, D3DXMATRIX projectionMatrix, ID3D11ShaderResourceView* texture, D3DXVECTOR4 clipPlane)
{
	HRESULT result;
	D3D11_MAPPED_SUBRESOURCE mappedResource;
	MatrixBufferType* dataPtr;
	unsigned int bufferNumber;
	ClipPlaneBufferType* dataPtr2;

	Graphics::D3DDevice* device = GetPlatform()->GetDevice()->As<Graphics::D3DDevice>();

	// Transpose the matrices to prepare them for the shader.
	D3DXMatrixTranspose(&worldMatrix, &worldMatrix);
	D3DXMatrixTranspose(&viewMatrix, &viewMatrix);
	D3DXMatrixTranspose(&projectionMatrix, &projectionMatrix);

	// Lock the matrix constant buffer so it can be written to.
	result = device->GetDeviceContext()->Map(mMatrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
	if(FAILED(result))
	{
		return false;
	}

	// Get a pointer to the data in the matrix constant buffer.
	dataPtr = (MatrixBufferType*)mappedResource.pData;

	// Copy the matrices into the matrix constant buffer.
	dataPtr->World = worldMatrix;
	dataPtr->View = viewMatrix;
	dataPtr->Projection = projectionMatrix;

	// Unlock the buffer.
	device->GetDeviceContext()->Unmap(mMatrixBuffer, 0);

	// Set the position of the matrix constant buffer in the vertex shader.
	bufferNumber = 0;

	// Now set the matrix constant buffer in the vertex shader with the updated values.
	device->GetDeviceContext()->VSSetConstantBuffers(bufferNumber, 1, &mMatrixBuffer);

	// Set shader texture resource in the pixel shader.
	device->GetDeviceContext()->PSSetShaderResources(0, 1, &texture);

	// Lock the clip plane constant buffer so it can be written to.
	result = device->GetDeviceContext()->Map(mClipPlaneBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
	if(FAILED(result))
	{
		return false;
	}

	// Get a pointer to the data in the clip plane constant buffer.
	dataPtr2 = (ClipPlaneBufferType*)mappedResource.pData;

	// Copy the clip plane into the clip plane constant buffer.
	dataPtr2->clipPlane = clipPlane;

	// Unlock the buffer.
	device->GetDeviceContext()->Unmap(mClipPlaneBuffer, 0);

	// Set the position of the clip plane constant buffer in the vertex shader.
	bufferNumber = 1;

	// Now set the clip plane constant buffer in the vertex shader with the updated values.
	device->GetDeviceContext()->VSSetConstantBuffers(bufferNumber, 1, &mClipPlaneBuffer);

	return true;
}